<template>
  <div>
    <input ref="folder" style="display:none" type="file" webkitdirectory @change.stop="changeData">
    <el-input v-model="folderPath" readonly>
      <el-button slot="append" icon="el-icon-folder" @click="selectFolder"/>
    </el-input>
    <div v-if="showFileList" class="folderFileList" :style="{height: fileListHeight}">
      <span v-for="item in fileList" :key="item.webkitRelativePath" style="display: block">
        {{ item.webkitRelativePath }}
      </span>
    </div>
  </div>
</template>

<script>
export default {
  name: 'FolderSelector',
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: Array,
      default: null
    },
    fileListHeight: {
      type: String,
      default: '150px'
    },
    showFileList: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileList: [],
      folderPath: ''
    }
  },
  computed: {
    fileListStyle() {
      return 'overflow-y:scroll;height:' + this.height + 'px;'
    }
  },
  methods: {
    selectFolder() {
      this.$refs.folder.click()
    },
    changeData() {
      const list = this.$refs.folder.files
      this.fileList = []
      if (list.length > 0) {
        const path = list[0].webkitRelativePath
        let i = path.indexOf('/')
        if (i === -1) {
          i = path.indexOf('\\')
        }
        if (i > 0) {
          this.folderPath = path.substr(0, i)
        }
        for (let i = 0; i < list.length; ++i) {
          this.fileList.push(list[i])
        }
      } else {
        this.folderPath = ''
      }
      this.$emit('change', this.fileList)
    },
    getFolder() {
      return this.folderPath
    }
  }
}
</script>

<style scoped>
.folderFileList {
  overflow-y: scroll;
}
</style>
